package com.example.system.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.user.entity.User;
import com.example.user.mapper.UserMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.HostUnauthorizedException;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author 贾明祯
 * @ClassName MyShiroRealm
 * @Date 2020/9/1 14:21
 * @Introduce
 */
public class MyShiroRealm  extends AuthorizingRealm{
    @Autowired
    private UserMapper userMapper;
    /**
      * @Author: 贾明祯
      * @Date: 2020/9/1 14:22
      * @Introduce: 授权
      */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        User user = (User) SecurityUtils.getSubject().getPrincipal();
//        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
//
//        // 权限
//        Set<String> permissions = new HashSet<>();
//        authorizationInfo.setStringPermissions(permissions);
//        System.out.println(permissions);
//        if (permissions.size() <= 0) {
//            throw new HostUnauthorizedException("没有权限");
//        }
//        return authorizationInfo;
        return null;
    }

    /**
      * @Author: 贾明祯
      * @Date: 2020/9/1 14:21
      * @Introduce: 认证登录
      */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken authToken = (UsernamePasswordToken) authenticationToken;
        String name = authenticationToken.getPrincipal().toString();
        String account=authToken.getUsername();
        QueryWrapper<User> ew = new QueryWrapper<User>();
        ew.eq("account",account);
        User user=userMapper.selectOne(ew);
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword().toString(), getName());
        SecurityUtils.getSubject().getSession().setAttribute("currentUser", user);
        return authenticationInfo;
    }
}
